import crypto from 'crypto';
import { query } from '@/lib/sqlite_db';

export class AdminAuthService {
  // 检查是否已设置密码
  async hasPasswordSet(): Promise<boolean> {
    try {
      const sql = `SELECT config_value FROM admin_config WHERE config_key = 'admin_password'`;
      const result = await query(sql);
      return result && result.length > 0;
    } catch (error) {
      console.error('检查密码设置失败:', error);
      return false;
    }
  }

  // 验证密码
  async verifyPassword(password: string): Promise<boolean> {
    try {
      const sql = `SELECT config_value FROM admin_config WHERE config_key = 'admin_password'`;
      const result = await query(sql);
      
      if (!result || result.length === 0) {
        return false;
      }
      
      const hashedPassword = result[0].config_value;
      const inputHashedPassword = crypto
        .createHash('md5')
        .update(password)
        .digest('hex');
      
      return hashedPassword === inputHashedPassword;
    } catch (error) {
      console.error('验证密码失败:', error);
      return false;
    }
  }

  // 设置密码
  async setPassword(password: string): Promise<void> {
    try {
      const hashedPassword = crypto
        .createHash('md5')
        .update(password)
        .digest('hex');
      
      // 检查是否已存在密码配置
      const checkSql = `SELECT config_key FROM admin_config WHERE config_key = 'admin_password'`;
      const existingConfig = await query(checkSql);
      
      if (existingConfig && existingConfig.length > 0) {
        // 更新现有密码
        const updateSql = `
          UPDATE admin_config
          SET config_value = ?
          WHERE config_key = 'admin_password'
        `;
        await query(updateSql, [hashedPassword]);
      } else {
        // 创建新密码配置
        const insertSql = `
          INSERT INTO admin_config (config_key, config_value)
          VALUES ('admin_password', ?)
        `;
        await query(insertSql, [hashedPassword]);
      }
    } catch (error) {
      console.error('设置密码失败:', error);
      throw error;
    }
  }

  // 更改密码
  async changePassword(oldPassword: string, newPassword: string): Promise<boolean> {
    try {
      // 首先验证旧密码
      const isOldPasswordValid = await this.verifyPassword(oldPassword);
      if (!isOldPasswordValid) {
        return false;
      }
      
      // 设置新密码
      await this.setPassword(newPassword);
      return true;
    } catch (error) {
      console.error('更改密码失败:', error);
      return false;
    }
  }
}